﻿#region Librerias

using System;
using System.Web;
using ESF.General;
using ESF.DMS.DataAccess.Search;
using ESF.General.Entity;
using ESF.DMS.Entities.Search;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using ESF.DMS.DataAccess;
using ESF.DMS.Entities;
using ESF.Web;
using ESF.SSO.Core.DataAccess.BasicReferences;
using System.Collections.Specialized;
using ESF.DMS.Entities.Load;
using ESF.DMS.DataAccess.Load;

#endregion


namespace Searcher
{
	public class SearchBrowser : IHttpHandler
	{
		#region Propiedades
		
		public bool IsReusable { get { return false; } }

		#endregion

	
		#region Process Request
	
		public void ProcessRequest (HttpContext pContext)
		{
			string methodName;

			Stopwatch sw = new Stopwatch ();
			sw.Start ();

			pContext.Response.ContentType = "text/plain";



			try
			{
				methodName = pContext.Request.QueryString ["_methodName"];

				switch (methodName)
				{
					case "SearchFiles":
						SearchFiles (pContext, sw);
					break;

					case "GetList":
						GetList (pContext, sw);
					break;

					case "GetImageCatalogsUploadExcelList":
						GetImageCatalogsUploadExcelList (pContext, sw);
					break;

					default:
						throw new Exception (string.Format ("The method {0} is not implemented", methodName));
				}
			}
			catch (Exception pEx)
			{
				pContext.Response.StatusCode = 500;
				pContext.Response.Write (Log.Error (pEx).Message);
			}
			finally
			{
				if (sw.IsRunning)
				{
					sw.Stop ();
				}
			}
		}

		#endregion


		#region Upload

		private void GetImageCatalogsUploadExcelList (HttpContext pContext, Stopwatch pSw)
		{
			List<IEnterprise> enterprises;

			List<SaludTotal_Red_Changes> changes;

			StringBuilder resultXML = new StringBuilder();

			XmlWriter xmlWriter = XmlWriter.Create (resultXML, new XmlWriterSettings () { OmitXmlDeclaration = true });

			
			AdoLoadFolderChanges.Verify_SaludTotal_Red_Changes (TextHelper.GetInt (pContext.Request.QueryString ["pMonitoredDirectoryID"]), out enterprises, out changes);

			xmlWriter.WriteStartElement ("UploadVerifyContents");
			
			foreach (IEnterprise ent in enterprises)
			{
				xmlWriter.WriteStartElement ("Enterprises");

					xmlWriter.WriteAttributeString ("Name", ent.Name);

					xmlWriter.WriteAttributeString ("IdentificationNumber", ent.IdentificationNumber);

					if (ent.IdentificationType != null)
					{
						xmlWriter.WriteAttributeString ("Code", ent.IdentificationType.Code);
					}

				xmlWriter.WriteEndElement ();
			}

			xmlWriter.WriteStartElement ("Changes");

			foreach (SaludTotal_Red_Changes chn in changes)
			{
				xmlWriter.WriteStartElement ("Change");

					xmlWriter.WriteAttributeString ("NIT", chn.NIT);
					xmlWriter.WriteAttributeString ("Sucursal", chn.Sucursal);
					xmlWriter.WriteAttributeString ("CarpetaVigente", chn.CarpetaVigente);
					xmlWriter.WriteAttributeString ("CarpetaHistorico", chn.CarpetaHistorico);
					xmlWriter.WriteAttributeString ("FechaVigencia", TextHelper.ToString(chn.FechaVigencia, TextHelper.DEFAULT_DATE_FORMAT));
					xmlWriter.WriteAttributeString ("NumeroHojas", chn.NumeroHojas.ToString());
					xmlWriter.WriteAttributeString ("TipoActualizacion", chn.TipoActualizacion);

				// TODO: analisis

				xmlWriter.WriteEndElement ();
			}

			xmlWriter.WriteEndElement ();

			xmlWriter.WriteEndElement ();

			xmlWriter.Close ();


			pContext.Response.ContentType = "text/xml";

			pContext.Response.Write(resultXML.ToString());

			pContext.Response.Cache.SetExpires(DateTime.Now);
			pContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
		}

		#endregion


		#region Methods

		private void SearchFiles (HttpContext pContext, Stopwatch pSw)
		{
			FileReference filter = new FileReference ();

			string xml;


			filter.Enterprise.IdentificationNumber = pContext.Request.QueryString ["pEnterpriseIdentificationNumber"];
			filter.Enterprise.Name = pContext.Request.QueryString["pEnterpriseName"];
			
			filter.MonitoredDirectory = new BasicReference () { ID = TextHelper.GetNullableInt (pContext.Request.QueryString["pMonitoredDirectoryID"]) };
			filter.MonitoredDirectorySubCategory = new BasicReference() { ID = TextHelper.GetNullableInt(pContext.Request.QueryString["pSubCatalogID"]) };

			filter.Levels = GetFilterLevels (pContext.Request.QueryString);

			xml =
				AdoFileReferenceSearchResult.QueryFileReferencesByWordContents(
					new PaggingInfo()
					{
						PageIndex = TextHelper.GetInt(pContext.Request.QueryString["pPageIndex"]),
						PageSize = TextHelper.GetInt(pContext.Request.QueryString["pPageSize"])
					},
					filter,
					TextHelper.Split(" ", pContext.Request.QueryString["pGeneralQuery"]).ToArray());
			
			//stbXML.Append(File.ReadAllText(pContext.Server.MapPath("~/Search/xslt/searchResultsGrid.xml")));

			pSw.Stop ();

			pContext.Response.Cache.SetExpires(DateTime.Now);
			pContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

			pContext.Response.ContentType = "text/xml";
			pContext.Response.Write(string.Format("<PFRs ProcessingDurationms=\"{0}\">{1}</PFRs>", pSw.ElapsedMilliseconds, xml));
		}
		

		private List<FileReferenceLevel> GetFilterLevels (NameValueCollection pQueryString)
		{
			FileReferenceLevel tmpFileReferenceLevel;
			List<FileReferenceLevel> tmpResult = new List<FileReferenceLevel> ();


			for (int levelUsed = 1; levelUsed <= TextHelper.GetInt(pQueryString ["pMaxLevelUsed"]); levelUsed++)
			{
				tmpFileReferenceLevel = new FileReferenceLevel()
				{
					Level = levelUsed,
					Name = pQueryString["pLevel_" + levelUsed]
				};

				if (!string.IsNullOrEmpty(tmpFileReferenceLevel.Name))
				{
					tmpResult.Add(tmpFileReferenceLevel);
				}
			}

			return tmpResult;
		}


		private void GetList(HttpContext pContext, Stopwatch pSw)
		{
			List<BasicReference> list = new List<BasicReference> ();

			StringBuilder resultJSON = new StringBuilder ();


			switch (pContext.Request.QueryString ["pListName"])
			{
				case "MonitoredDirectory":
					list = AdoFileReference.GetMonitoredDirectories ();
				break;


				case "SubCatalog":
					BasicReference filterBR = new BasicReference ();

					filterBR.ID = TextHelper.GetNullableInt (pContext.Request.QueryString ["pMonitoredDirectoryID"]);


					if (filterBR.ID != null)
					{
						list = AdoBasicReference.GetChildrenBasicReferences(filterBR, 3001);
					}
				break;


				case "FileReferenceLevel":
					FileReferenceLevel filterFR = new FileReferenceLevel ();

					filterFR.Level = int.Parse (pContext.Request.QueryString ["pLevel"]);
					filterFR.FileReference.MonitoredDirectory.ID = int.Parse (pContext.Request.QueryString ["pMonitoredDirectoryID"]);

					list = AdoFileReferenceLevel.List (filterFR, GetFilterLevels (pContext.Request.QueryString));
				break;

				default:
					throw new NotSupportedException (string.Format ("List \"{0}\" is not supported", pContext.Request.QueryString ["pListName"]));
			}

			resultJSON.Append ("[");

			if (!DataHelper.IsEmpty(list))
			{	
				foreach (BasicReference item in list)
				{
					resultJSON.Append ("{");
				
					if (item.ID != null)
					{
						resultJSON.AppendFormat ("ID:{0},", item.ID);
					}

					if (!string.IsNullOrWhiteSpace (item.Code))
					{
						resultJSON.AppendFormat ("Code:\"{0}\",", JS.ClearMessage (item.Code));
					}

					resultJSON.AppendFormat("Name:\"{0}\"", JS.ClearMessage(item.Name));

					resultJSON.Append ("},");
				}

				resultJSON.Length--;
			}
			
			resultJSON.Append ("]");

			pContext.Response.Write (resultJSON.ToString ());

			pContext.Response.Cache.SetExpires(DateTime.Now);
			pContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
		}

		#endregion
	}
}